﻿using System.Collections.Generic;
using System.Linq;
using Fujitsu.JiraAnalysis.DAL;
using Fujitsu.JiraAnalysis.ReplicationService.SynchronizeExceptions;
using Fujitsu.JiraAnalysis.TrackingSystemAdapter;
using Fujitsu.JiraAnalysis.JiraRPC;

namespace Fujitsu.JiraAnalysis.ReplicationService.Synchronize
{
    class IssueResolutionSync: SyncBase<RemoteResolution, ResolutionMapping>
    {
        ResolutionStorage resolutionStorage = new ResolutionStorage();

        protected override SyncException GetSyncException(string projectName, int projectId, string projectKey)
        {
            return new IssueResolutionSyncException(projectName, projectId, projectKey);
        }

        protected override List<ResolutionMapping> GetStorageItems(int projectId)
        {
            return resolutionStorage.GetIssueResolutionMappingForProject(projectId);
        }

        protected override List<RemoteResolution> GetTrackSystemInfoItems(Project project, ITrackSystemInfo adapter)
        {
            return adapter.GetResolutions();
        }

        protected override ResolutionMapping FindMatchInStorage(List<ResolutionMapping> storageItems, RemoteResolution trackSystemInfoItem, int projectId)
        {
            return storageItems.FirstOrDefault(i => i.JiraResolutionID.ToString() == trackSystemInfoItem.id && i.ProjectID == projectId);
        }

        protected override void Update(RemoteResolution trackSystemItem, ResolutionMapping resolutionMapping)
        {
            if (resolutionMapping.Name == trackSystemItem.name)
                return;
            resolutionStorage.UpdateResolutionName(resolutionMapping.ProjectID, resolutionMapping.JiraResolutionID, trackSystemItem.name);
        }
    }
}
